package com.qtummatrix.service.servlet;

import com.qtummatrix.dao.daoImpl.UserDaoImpl;
import com.qtummatrix.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;

@WebServlet("/switchPageServlet")
public class SwitchPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取是哪一个操作，上一页、下一页、首页、尾页
        String info = request.getParameter("info");
        //获取当前页码
        String pageNumber = request.getParameter("pageNumber");

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        int operationUserId = user.getId();

        LinkedList<Map> maps = null;
        UserDaoImpl userDao = new UserDaoImpl();

        //查看有多少条记录信息
        int personNum = userDao.selectTotalPerson();
        //查看一共有多少页
        int totalPage = personNum % 6 == 0 ? personNum / 6 : personNum / 6 + 1;
        int s = 0;
        switch (info) {
            case "首页":
                s = 1;
                maps = userDao.selectUserInfo(operationUserId, 0);
                break;
            case "上一页":
                s = Integer.parseInt(pageNumber);
                maps = userDao.getPrevious(operationUserId, s);
                s = maps == null ? s : s - 1;
                break;
            case "下一页":
                s = Integer.parseInt(pageNumber);
                maps = userDao.getNextPage(operationUserId, s);
                s = maps == null ? s : s + 1;
                break;
            case "尾页":
                s = totalPage;
                maps = userDao.selectUserInfo(operationUserId, (totalPage - 1) * 6);
                break;
        }
        if (maps == null) {
            //重定向到页面
            request.setAttribute("error", "数据错误，返回...");
            request.getRequestDispatcher("showAllUserInfoServlet").forward(request, response);
        } else {
            //显示数据给页面
            request.setAttribute("key_userList", maps);
            //当前页码
            request.setAttribute("pageNumber", s);
            //总共的页数
            request.setAttribute("pagetotalNumber", totalPage);
            //总共多少条记录
            request.setAttribute("totalNumber", personNum);

            //转发到employeemanage.jsp
            request.getRequestDispatcher("employeemanage.jsp").forward(request, response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        this.doPost(request, response);
    }
}
